package com.liuqi.aiagent.controller;

import com.liuqi.aiagent.service.TokensUsageService;
import com.liuqi.aiagent.transfer.ApiResult;
import com.liuqi.aiagent.transfer.dto.TokensUsageFindDto;
import com.liuqi.aiagent.transfer.model.Result;
import com.liuqi.aiagent.util.DateUtil;
import com.liuqi.aiagent.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.time.LocalDate;
import java.time.YearMonth;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liuqi
 * @date 2025/7/24
 **/
@RestController
@RequestMapping("/tokens/usage")
@AllArgsConstructor
@Api(tags = "Token计量")
@Slf4j
public class TokensUsageController {

    private final TokensUsageService tokensUsageService;

    @ApiOperation("查询tokens计量统计信息")
    @PostMapping("/statistics")
    public Result statistics(@RequestBody TokensUsageFindDto findDto) {
        if (StringUtil.notHasText(findDto.getBeginDate())) {
            return ApiResult.fail("起始日期为空");
        }
        if (StringUtil.notHasText(findDto.getEndDate())) {
            return ApiResult.fail("结束日期为空");
        }
        if (findDto.getDateType() == TokensUsageFindDto.DateType.MONTH) {
            findDto.setBeginDate(
                    YearMonth.parse(findDto.getBeginDate(), DateUtil.Y_M)
                            .atDay(1)
                            .format(DateUtil.Y_M_D)
            );
            findDto.setEndDate(
                    YearMonth.parse(findDto.getEndDate(), DateUtil.Y_M)
                            .atEndOfMonth()
                            .format(DateUtil.Y_M_D)
            );
        }

        return tokensUsageService.statistics(findDto);
    }

}
